<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid;
      }
    </style>
  </head>

  <body>
    <canvas class="box" width="500" height="500"></canvas>
    <script>
      let imgArr = [
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp05%2F1Z9291TIBZ6-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1666572976&t=1c23f2728d501dd54fd553653f1b4d45",
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Ffile02.16sucai.com%2Fd%2Ffile%2F2014%2F0829%2F372edfeb74c3119b666237bd4af92be5.jpg&refer=http%3A%2F%2Ffile02.16sucai.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1666572977&t=99cc5fffe60b0924f80078b3bf8fec17",
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2F1011%2F010QG05111%2F1F10Q05111-3.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1666572977&t=77fb8ffbf465a0b270ac63990cdb3f89",
      ]; // 存放图片的地址，给图片做预加载，提前把图片加载完毕，之后再使用
      function loadImg(imgArr) {
        return new Promise((resolve, reject) => {
          let resArr = new Array(imgArr.length);
          let count = 0;
          imgArr.forEach((src, index) => {
            let imgEle = new Image();
            imgEle.src = src;
            imgEle.onload = function () {
              resArr[index] = this;
              count++;
              if (count === imgArr.length) {
                resolve(resArr);
              }
            };
          });
        });
      }
      let canvas = document.querySelector(".box");
      let ctx = canvas.getContext("2d");
      loadImg(imgArr).then((res) => {
        ctx.drawImage(res[0], 0, 0, 100, 100);
        ctx.drawImage(res[1], 150, 0, 100, 100);
        ctx.drawImage(res[2], 300, 0, 100, 100);

      });
    </script>
  </body>
</html>
